package cn.wolfcode.luowowo.redis.Service.impl;

import cn.wolfcode.luowowo.domain.Strategy;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.enum1.RedisKeys;
import cn.wolfcode.luowowo.redis.Service.IUserInfoRedisService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.service.IUserInfoService;
import cn.wolfcode.luowowo.util.Consts;
import cn.wolfcode.luowowo.util.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IStrategyService strategyService;

    public void sendVerifyCode(String phone,String code){
        //String key =  "verify_code:" + phone
        String key = RedisKeys.VERIFY_CODE.join(phone);
        //设置验证码缓存,5分钟
        redisTemplate.opsForValue().set(key,code, RedisKeys.VERIFY_CODE.getTime());
    }

    @Override
    public String selectByKey(String phone) {
        String key = "verify_code:" + phone;
        return  redisTemplate.opsForValue().get(key);
    }

    /**
     * 创建唯一字符串token = UUID,token作为redis的key,userInfo作为value存入库,时间为30分钟
     * 返回JsonResult,将token带到浏览器中
     * @param userInfo
     * @return
     */
    @Override
    public String getToken(UserInfo userInfo) {
        //创建token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        //设置key添加到redis库中,先将userInfo对象转换为Json
        String s = JSON.toJSONString(userInfo);
        //给token加个前缀
        String key = RedisKeys.LOGIN_TOKEN.join(token);
        redisTemplate.opsForValue().set(key,s,RedisKeys.LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
        //返回token
        return token;

    }

    /**
     * 通过token获取当前用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfo getUserByToken(String token) {
        //判断是否有长度
        if(!StringUtils.hasLength(token)){
            return null;
        }
        //通过token获取key
        String key = RedisKeys.LOGIN_TOKEN.join(token);
        //通过key去获取value
        String user = redisTemplate.opsForValue().get(key);
        //如果user有长度的话将user转换成user对象返回
        if(StringUtils.hasLength(user)){
            UserInfo userInfo = JSON.parseObject(user, UserInfo.class);
            return userInfo;
        }
        return null;
    }

    @Override
    public UserInfo setView(String id, UserInfo userInfo) {
        List ids = new ArrayList<>();
        Date date = new Date();
        Date endDate = DateUtil.getEndDate(date);
        long time = DateUtil.getDateBetween(date, endDate);
        //获取当前登录id
        String uid = userInfo.getId();
        //获取key
        String key = RedisKeys.USER.join(id);
        //通过id查用户
        if (StringUtils.hasLength(id)) {
            UserInfo userInfo1 = userInfoService.selectById(id);
            //获取u的users集合,mongodb中
            List<UserInfo> us = userInfo1.getUsers();
            //判断id跟uid是否一致
            if (!(id.equals(uid))) {
                //只有当不是自己访问的时候才会进入下面判断
                if (redisTemplate.hasKey(key)) {
                    //获取value
                    String s = redisTemplate.opsForValue().get(key);
                    ids = JSON.parseArray(s);
                    if (!(ids.contains(uid))) {
                        //id设置进集合中,mongodb中
                        us.add(userInfoService.selectById(uid));
                        //id设置进集合中,redis中
                        ids.add(uid);
                        //再重新设置key里面的值
                        redisTemplate.opsForValue().set(key, JSON.toJSONString(ids));
                        //设置累计访问数+1
                        userInfo1.setTotalView(userInfo1.getTotalView() + 1);
                        //设置今天访问数+1
                        userInfo1.setTodayView(userInfo1.getTodayView() + 1);
                    }
                } else {
                    //id设置进集合中,mongodb中
                    us.add(userInfoService.selectById(uid));
                    //如果没有key的话,自己设置一个并设置时间
                    ids.add(uid);//redis中的list
                    redisTemplate.opsForValue().set(key, JSON.toJSONString(ids), time, TimeUnit.SECONDS);
                    //设置今天访问数为0
                    userInfo1.setTodayView(0);
                    //设置累计访问数+1
                    userInfo1.setTotalView(userInfo1.getTotalView() + 1);
                    //设置今天访问数+1
                    userInfo1.setTodayView(userInfo1.getTodayView() + 1);
                }
            }else{
                //自己访问的话
                if (redisTemplate.hasKey(key)) {
                    //获取value
                    String s = redisTemplate.opsForValue().get(key);
                    ids = JSON.parseArray(s);
                }
            }

            //定义一个用户等于这个用户对象
            UserInfo u = userInfo1;
            //将us设置进用户中
            u.setUsers(us);
            //更新mongodb数据库
            userInfoService.update(u);
            //通过ids查询用户集合
            List<UserInfo> users = userInfoService.fingByIdIn(ids);
            //将users设置进用户中
            userInfo1.setUsers(users);
            return userInfo1;
        }
        return null;
    }

    @Override
    public List<Strategy> getStrategies(String id) {
        //根据用户id查询用户收藏
        //获取key
        String key = RedisKeys.STRATEGY_FAVORNUM.join(id);
        //通过key获取value
        String s = redisTemplate.opsForValue().get(key);
        List sids = JSON.parseArray(s);
        //通过攻略id查询攻略
        List<Strategy> strategies = strategyService.selectByIds(sids);
        return strategies;

    }
}
